<template>
    <div class="form-box">
        <div class="form-title-box">
            <h2 class="form-title-center">{{ isRegister ? '注册' : '登录' }}</h2>
        </div>
        <el-form :model="form" :rules="rules" ref="formRef" label-width="0" class="form-flex">
            <el-form-item prop="username" class="form-item-flex">
                <el-input v-model="form.username" placeholder="用户名" class="input-long" />
            </el-form-item>
            <el-form-item prop="password" class="form-item-flex">
                <el-input v-model="form.password" type="password" placeholder="密码" class="input-long" />
            </el-form-item>
            <el-form-item v-if="isRegister" prop="confirmPassword" class="form-item-flex">
                <el-input v-model="form.confirmPassword" type="password" placeholder="确认密码" class="input-long" />
            </el-form-item>
            <el-form-item class="form-item-flex">
                <el-button type="primary" class="submit-btn" @click="onSubmit">
                    {{ isRegister ? '注 册' : '登 录' }}
                </el-button>
            </el-form-item>
            <el-form-item v-if="!isRegister" class="form-item-flex">
                <a class="forgot" href="#">忘记密码?</a>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { authApi } from '../api/auth'

const router = useRouter()
const userStore = useUserStore()

const props = defineProps({
    isRegister: Boolean
})
const emit = defineEmits(['switch'])

const formRef = ref()
const form = ref({
    username: '',
    password: '',
    confirmPassword: ''
})

const validateConfirm = (rule, value, callback) => {
    if (props.isRegister && value !== form.value.password) {
        callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}

const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: props.isRegister, message: '请确认密码', trigger: 'blur' },
        { validator: validateConfirm, trigger: 'blur' }
    ]
}

watch(() => props.isRegister, () => {
    form.value.username = ''
    form.value.password = ''
    form.value.confirmPassword = ''
})

const onSubmit = () => {
    formRef.value.validate(async (valid) => {
        if (!valid) return
        try {
            if (props.isRegister) {
                const res = await authApi.register({
                    username: form.value.username,
                    password: form.value.password
                })
                if (res.data.code === 1000) {
                    ElMessage.success('注册成功，请登录')
                    emit('switch')
                } else {
                    ElMessage.error(res.data.msg || '注册失败')
                }
            } else {
                const res = await authApi.login({
                    username: form.value.username,
                    password: form.value.password
                })
                if (res.data.code === 1000) {
                    ElMessage.success('登录成功')
                    userStore.setToken(res.data.data) // pinia 存储 token
                    // 登录成功后获取用户信息
                    await userStore.fetchUserInfo()
                    router.push('/')
                } else {
                    ElMessage.error(res.data.msg || '登录失败')
                }
            }
        } catch (e) {
            ElMessage.error(e?.response?.data?.message || '操作失败')
        }
    })
}
</script>

<style scoped>
.form-box {
    width: 520px;
    padding: 48px 36px;
    background: #f8fbff;
    border-radius: 20px;
    box-shadow: 0 4px 24px rgba(126, 200, 227, 0.08);
    display: flex;
    flex-direction: column;
    align-items: center;
}

.form-title-box {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 36px;
}

.form-title-center {
    width: 400px;
    margin-left: 154px;
    font-size: 40px;
    letter-spacing: 12px;
    font-weight: 500;
    color: #3a5a7c;
    text-align: left;
    display: block;
}

h2 {
    font-size: 40px;
    letter-spacing: 12px;
    font-weight: 500;
    color: #3a5a7c;
    text-align: center;
    margin: 0;
}

.form-flex {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 18px;
}

.form-item-flex {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}

.input-long {
    width: 400px;
    height: 48px;
    font-size: 18px;
    border-radius: 8px;
    background: #e3f0ff;
    border: 1px solid #e0eaff;
    color: #3a5a7c;
}

.input-long:focus {
    border-color: #7ec8e3;
    background: #fff;
}

.submit-btn {
    width: 400px;
    height: 48px;
    font-size: 20px;
    border-radius: 24px;
    background: linear-gradient(90deg, #7ec8e3 0%, #b6e0fe 100%);
    color: #fff;
    letter-spacing: 10px;
    border: none;
    transition: transform 0.2s, box-shadow 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(126, 200, 227, 0.10);
}

.submit-btn:hover {
    transform: scale(1.04);
    box-shadow: 0 2px 12px rgba(126, 200, 227, 0.18);
}

.forgot {
    color: #7ec8e3;
    font-size: 14px;
    text-decoration: none;
    margin-left: 10px;
}
</style>